﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common
{
	public static class StringExtension
	{
		public static int LeftToken(this StringBuilder sb, int index, char token)
		{
			if (sb.Length != 0 && sb.Length - 1 >= index)
			{
				int retIndex = index;
				while (sb[retIndex] != token)
				{
					retIndex--;
				}
				return retIndex;
			}
			return -1;
		}

		public static int RightToken(this StringBuilder sb, int index, char token)
		{
			if (sb.Length != 0 && sb.Length - 1 >= index)
			{
				int retIndex = index;
				while (sb[retIndex] != token)
				{
					retIndex++;
				}
				return retIndex;
			}
			return -1;
		}

		public static int IndexOf(this StringBuilder sb, string value, int startIndex)
		{
			return IndexOf(sb, value, startIndex, false);
		}

		/// <summary>
		/// Get index of a string from a given index with case option
		/// </summary>
		/// <param name="sb"></param>
		/// <param name="text"></param>
		/// <param name="startIndex"></param>
		/// <param name="ignoreCase"></param>
		/// <returns></returns>

		public static int IndexOf(this StringBuilder sb, string value, int startIndex, bool ignoreCase)
		{
			int num3;
			int length = value.Length;
			int num2 = (sb.Length - length) + 1;
			if (ignoreCase == false)
			{
				for (int i = startIndex; i < num2; i++)
				{
					if (sb[i] == value[0])
					{
						num3 = 1;
						while ((num3 < length) && (sb[i + num3] == value[num3]))
						{
							num3++;
						}
						if (num3 == length)
						{
							return i;
						}
					}
				}
			}
			else
			{
				for (int j = startIndex; j < num2; j++)
				{
					if (char.ToLower(sb[j]) == char.ToLower(value[0]))
					{
						num3 = 1;
						while ((num3 < length) && (char.ToLower(sb[j + num3]) == char.ToLower(value[num3])))
						{
							num3++;
						}
						if (num3 == length)
						{
							return j;
						}
					}
				}
			}
			return -1;
		}

		/// <summary>
		/// Determine whether a string is begin with a given text
		/// </summary>
		/// <param name="sb"></param>
		/// <param name="value"></param>
		/// <param name="startIndex"></param>
		/// <param name="ignoreCase"></param>
		/// <returns></returns>
		public static bool StartsWith(this StringBuilder sb, string value, int startIndex, bool ignoreCase)
		{
			int length = value.Length;
			int num2 = startIndex + length;
			if (ignoreCase == false)
			{
				for (int i = startIndex; i < num2; i++)
				{
					if (sb[i] != value[i - startIndex])
					{
						return false;
					}
				}
			}
			else
			{
				for (int j = startIndex; j < num2; j++)
				{
					if (char.ToLower(sb[j]) != char.ToLower(value[j - startIndex]))
					{
						return false;
					}
				}
			}
			return true;
		}

	}
}
